package com.example.eos.service;

import com.example.eos.bean.ReturnInfo;
import com.example.eos.bean.User;
import com.example.eos.bean.UserLabel;
import com.example.eos.mapper.LabelMapper;
import com.example.eos.mapper.UserLabelMapper;
import com.example.eos.mapper.UserMapper;
import com.example.eos.tool.GlobalParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserLabelService {

    private UserLabelMapper userLabelMapper;
    private UserMapper userMapper;
    private LabelMapper labelMapper;

    @Autowired
    public UserLabelService(UserLabelMapper userLabelMapper, UserMapper userMapper, LabelMapper labelMapper){
        this.userLabelMapper = userLabelMapper;
        this.userMapper = userMapper;
        this.labelMapper = labelMapper;
    }

    //查询用户的标签
    public ReturnInfo findUserLabel(String userid){
        if(userMapper.findByUserid(userid)==null){
            return ReturnInfo.info2("用户不存在","");
        }else {
            List<UserLabel> userLabels = userLabelMapper.findByUserid(userid);
            List<UserLabel> userLabelList = new ArrayList<>();
            for(UserLabel userLabel : userLabels){
                if(labelMapper.findByLabelid(userLabel.getLabelid())!=null){
                    UserLabel userLabel1 = new UserLabel(userLabel.getLabelid(),labelMapper.findByLabelid(userLabel.getLabelid()).getLabelname());
                    userLabelList.add(userLabel1);
                }else {
                    userLabelMapper.deteleByUserlabelid(userLabel.getUserlabelid());
                }
            }
            return ReturnInfo.info2("成功",userLabelList);
        }
    }

    //用户添加标签
    public ReturnInfo addUserLabel(String labelid){
        Subject subject = SecurityUtils.getSubject();
        User user =(User) subject.getPrincipal();
        if(labelMapper.findByLabelid(labelid)==null){
            return ReturnInfo.info1("标签不存在");
        }
        if(userLabelMapper.findByUseridAndLabelid(user.getUserid(),labelid)!=null){
            return ReturnInfo.info1("用户已有该标签");
        }
        UserLabel userLabel = new UserLabel(GlobalParam.getUUID(),user.getUserid(),labelid,labelMapper.findByLabelid(labelid).getLabelname(),userLabelMapper.findCountByUserid(user.getUserid())+1);
        userLabelMapper.save(userLabel);
        return ReturnInfo.info1("成功");
    }

    //用户删除标签
    public ReturnInfo deleteUserLabel(String labelid){
        if(labelMapper.findByLabelid(labelid)==null){
            return ReturnInfo.info1("标签不存在");
        }
        Subject subject = SecurityUtils.getSubject();
        User user =(User) subject.getPrincipal();
        userLabelMapper.deteleByUseridAndLabelid(user.getUserid(),labelid);
        return ReturnInfo.info1("成功");
    }

}
